﻿using System;
using Aquarinum.Base.Exception;
using Aquarinum.Base.Infrastructure.Ioc;
using Aquarinum.Base.Infrastructure.WebSocket.Interface;
using Aquarinum.Base.Infrastructure.WebSocket.MessageHandler;
using Aquarinum.Base.Service.Http;
using Aquarinum.Util.Interface.Log;
using Aquarinum.WebSocekt.Core.Dtos;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ApiResultCode = Aquarinum.Base.Exception.ApiResultCode;

namespace Aquarinum.WebSocket.Server.Controllers
{
    /// <summary>
    ///     消息发送
    ///     todo 授权
    /// </summary>
    [Route("Api/WebSocket/Message")]
    public class MessageSendController : AquarinumApiController
    {
        private readonly IMessageSendProxy _messageSendProxy;

        public MessageSendController(IMessageSendProxy messageSendProxy)
        {
            _messageSendProxy = messageSendProxy;
        }

        /// <summary>
        ///     发送消息
        /// </summary>
        /// <returns></returns>
        [HttpPost("Send")]
        public bool SendMessage([FromBody] WebsocketMessageDto message)
        {
            var handlers = MessageHandleStrategyFactory.GetInstance().GetStrategyInstance(message.Type);
            try
            {
                foreach (var handler in handlers) handler.HandleMessage(message);
            }
            catch (Exception ex)
            {
                throw new BaseApiException(ApiResultCode.ServiceUnavailable,
                    $"websocket消息：{JsonConvert.SerializeObject(message)}出错", ex);
            }
            return true;
        }

        /// <summary>
        ///     发送回执
        /// </summary>
        /// <returns></returns>
        [HttpPost("Receipt")]
        public bool ReceiptMessage([FromBody] ReceiptMessageDto message)
        {
            _messageSendProxy.SendReceiptAsync(message.SourceMessage.From, message);
            return true;
        }
    }
}